package com.lcw.lostandfound.service.Impl;

import com.lcw.lostandfound.mapper.CommentMapper;
import com.lcw.lostandfound.pojo.Comment;
import com.lcw.lostandfound.service.CommentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    //存放迭代找出的所有子代的集合
    private List<Comment> tempReplys = new ArrayList<>();

    @Override
    public List<Comment> listCommentByGoodsId(Integer goodsId) {
        //查询出父节点
        List<Comment> comments = commentMapper.findByGoodsIdParentIdNull(goodsId, -1);
        for(Comment comment : comments){
            Integer id = comment.getCommentId();
            Integer userId = comment.getUserId();
            System.out.println(comment);
            List<Comment> childComments = commentMapper.findByGoodsIdParentIdNotNull(goodsId,id);
//            查询出子评论
            combineChildren(goodsId, childComments,userId);
            comment.setReplyComments(tempReplys);
            tempReplys = new ArrayList<>();
        }
        return comments;
    }

    private void combineChildren(Integer goodsId,List<Comment> childComments,Integer userId) {
        //        判断是否有一级子评论
        if(childComments.size() > 0){
//                循环找出子评论的id
            for(Comment childComment : childComments){
                Integer userId1 = childComment.getUserId();
                childComment.setParentId(userId);
                tempReplys.add(childComment);
                Integer childId = childComment.getCommentId();
//                    查询出子二级评论
                recursively(goodsId, childId, userId1);
            }
        }
    }

    private void recursively(Integer goodsId, Integer childId, Integer userId1) {
//        根据子一级评论的id找到子二级评论
        List<Comment> replayComments = commentMapper.findByGoodsIdAndReplayId(goodsId,childId);

        if(replayComments.size() > 0){
            for(Comment replayComment : replayComments){
                Integer userId = replayComment.getUserId();
                replayComment.setParentId(userId1);
                Integer replayId = replayComment.getCommentId();
                tempReplys.add(replayComment);
                recursively(goodsId,replayId,userId);
            }
        }
    }
    @Override
    public int saveComment(Comment comment) {
        return commentMapper.saveComment(comment);
    }

    @Override
    public int deleteComment(Integer id) {
        return commentMapper.deleteComment(id);
    }
}
